#include <stdio.h>
#include <pwd.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>

struct passwd* my_getpwnam(const char *name){
    struct passwd* pwdPtr, * pwd;
    pwdPtr = malloc(sizeof(struct passwd));
    if(pwdPtr == NULL){
        printf("Error malloc struct passwd %d %s\n", errno, strerror(errno));
        return NULL;
    }
    while((pwd = getpwent()) != NULL){
        if(strcmp(pwd->pw_name, name) == 0){
            endpwent();
            pwdPtr->pw_name = malloc(strlen(pwd->pw_name));
            if(pwdPtr->pw_name == NULL){
                printf("Error malloc pwdPtr->pw_name  %d %s\n", errno, strerror(errno));
                return NULL;
            }
            strcpy(pwdPtr->pw_name, pwd->pw_name);

            pwdPtr->pw_passwd = malloc(strlen(pwd->pw_passwd));
            if(pwdPtr->pw_passwd == NULL){
                printf("Error malloc pwdPtr->pw_passwd  %d %s\n", errno, strerror(errno));
                return NULL;
            }
            strcpy(pwdPtr->pw_passwd, pwd->pw_passwd);

            pwdPtr->pw_dir = malloc(strlen(pwd->pw_dir));
            if(pwdPtr->pw_dir == NULL){
                printf("Error malloc pwdPtr->pw_dir  %d %s\n", errno, strerror(errno));
                return NULL;
            }
            strcpy(pwdPtr->pw_dir, pwd->pw_dir);

            pwdPtr->pw_shell = malloc(strlen(pwd->pw_shell));
            if(pwdPtr->pw_shell == NULL){
                printf("Error malloc pwdPtr->pw_shell  %d %s\n", errno, strerror(errno));
                return NULL;
            }
            strcpy(pwdPtr->pw_shell, pwd->pw_shell);

            pwdPtr->pw_gecos = malloc(strlen(pwd->pw_gecos));
            if(pwdPtr->pw_gecos == NULL){
                printf("Error malloc pwdPtr->pw_gecos  %d %s\n", errno, strerror(errno));
                return NULL;
            }
            strcpy(pwdPtr->pw_gecos, pwd->pw_gecos);
            pwdPtr->pw_uid = pwd->pw_uid;
            pwdPtr->pw_gid = pwd->pw_gid;
            return pwdPtr;
        }
    }

    return NULL;
}
int main(){
    struct passwd* pwd;
    pwd = my_getpwnam("UserName");
    if(pwd == NULL){
        puts("Returned null, you user not exists");
        exit(EXIT_SUCCESS);
    }

    printf("pw_name %s\n pw_uid %d \n pw_gid %d \n pw_passwd %s \n pw_dir %s\n pw_shell %s \n pw_gecos %s \n",pwd->pw_name, pwd->pw_uid, pwd->pw_gid,  pwd->pw_passwd, pwd->pw_dir, pwd->pw_shell, pwd->pw_gecos);
    
    free(pwd->pw_dir);
    free(pwd->pw_gecos);
    free(pwd->pw_name);
    free(pwd->pw_passwd);
    free(pwd->pw_shell);
    free(pwd);
    exit(EXIT_SUCCESS);
}